package com.sfdk.admin.structure
{
import com.sfdk.data.api.ITreeDataProvider;

public class TreeNode
	{
		private var _children:Vector.<TreeNode>;
				
		public function TreeNode(label : String)
		{
			_name = label;
			_children = new Vector.<TreeNode>();
			_isLeaf = false;
		}
		
		// ------------------------------------------ //
		//											  //
		// 				   proprerties				  //
		//											  //
		// ------------------------------------------ //
		
		private var _name:String;
		
		public function get name():String
		{
			return _name;
		}
		
		public function set name(value:String):void
		{
			_name = value;
		}
		
		private var _data : ITreeDataProvider;

		public function get data():ITreeDataProvider
		{
			return _data;
		}
		
		public function set data(value:ITreeDataProvider):void
		{
			_data = value;
		}
		
		private var _isLeaf : Boolean;
		
		public function get isLeaf():Boolean
		{
			return _isLeaf;
		}
		
		public function set isLeaf(value:Boolean):void
		{
			_isLeaf = value;
		}
		
		public function getChildByName(name : String) : TreeNode
		{
			var treeNode : TreeNode;
			var child : TreeNode;
			for each(treeNode in _children)
			{
				if(treeNode.name == name)
					return treeNode;
				else
				{
					child = treeNode.getChildByName(name);
					if(child != null)
						return child;
				}
			}
			return null;
		}
		
		public function addChild(node : TreeNode) : void
		{
			_children.push(node);
		}
		
		public function bindData(imageData : ITreeDataProvider) : void
		{
			_data = imageData;
			_isLeaf = true;
		}
		
		public function write() : XML
		{
			var xml :XML;
			if(!_isLeaf)
			{
				if(_name == "root")
					xml = new XML("<root></root>");
				else if(_data != null)
					xml = new XML('<rep label="'+_name+'" data="'+_data.label+'" type="'+_data.type+'"></rep>');
				else
					xml = new XML('<rep label="'+_name+'" data="'+_name+'" type="'+_name+'"></rep>');
			}
			else
			{
				xml = new XML('<leaf label="'+_name+'" data="'+_data.label+'" type="'+_data.type+'"></leaf>');
			}
			var subXML : XML;
			if(!_isLeaf)
			{
				for(var i : int = 0; i < _children.length; i++)
				{
					subXML = _children[i].write();
					xml.appendChild(subXML);
				}
			}
			return xml;
		}
	}
}